<?php

/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace common\rest\actions\auth;

use Yii;
use yii\web\ServerErrorHttpException;
use yii\rest\Action;
use common\rest\statics\ResponseDatum;
use common\rest\base\WxException;
use common\rest\statics\OperationResult;
/**
 * DeleteAction implements the API endpoint for deleting a model.
 *
 * For more details and usage information on DeleteAction, see the [guide article on rest controllers](guide:rest-controllers).
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class DeleteAction extends Action {

    /**
     * auth id
     * @var string 
     */
    public $authIdAttribute = "user_id";

    /**
     * Deletes a model.
     * @param mixed $id id of the model to be deleted.
     * @throws ServerErrorHttpException on failure.
     */
    public function run($id) {
        try {
            $modelClass = $this->modelClass;
            $model = $modelClass::findOne([
                        'id' => $id,
                        $this->authIdAttribute => Yii::$app->user->id,
            ]);
            $params = Yii::$app->getRequest()->getBodyParams();

            if (is_null($model)) {
                throw new WxException(Yii::t('app.rest', 'Resource not found!'), OperationResult::ERROR_404, $params, null);
            }

            $model->load($params);
            if ($model->delete()) {
                return ResponseDatum::getSuccessDatum(['msg' => Yii::t('app.c2', 'Operation completed successfully!')], $model);
            } else {
                throw new WxException(Yii::t('app.rest', 'Failed to delete the object for unknown reason.'), OperationResult::ERROR_600, $params, null);
            }
        } catch (WxException $ex) {
            return ResponseDatum::getErrorDatum([
                        'code' => $ex->getCode(),
                        'msg' => $ex->getMessage(),
                        'extraData' => $ex->extraData,
                            ], $ex->data);
        }
    }

}
